<template>
  <div class="container">
    <header>
      <h1>Vue 2 + ECharts 饼状图</h1>
      <p class="subtitle">Vue.js (2.6.12) + ECharts (5.4.0)</p>
    </header>
    
    <div class="controls">
      <button 
        class="btn" 
        :class="{active: chartType === 'basic'}" 
        @click="changeChartType('basic')"
      >
        <i class="fas fa-chart-pie"></i> 基础饼图
      </button>
      <button 
        class="btn" 
        :class="{active: chartType === 'doughnut'}" 
        @click="changeChartType('doughnut')"
      >
        <i class="fas fa-donate"></i> 环形图
      </button>
      <button 
        class="btn" 
        :class="{active: chartType === 'rose'}" 
        @click="changeChartType('rose')"
      >
        <i class="fas fa-certificate"></i> 南丁格尔玫瑰图
      </button>
    </div>
    
    <div class="charts-container">
      <!-- 主图表 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="chart-icon">
            <i class="fas fa-chart-pie"></i>
          </div>
          <h2 class="chart-title">{{ getChartTitle() }}</h2>
        </div>
        <div class="chart-wrapper" ref="pieChart"></div>
        
        <div class="data-controls">
          <h3>数据控制</h3>
          <div class="control-group">
            <label>
              数据系列数量: {{ seriesCount }}
              <span class="range-value">{{ seriesCount }}</span>
            </label>
            <input type="range" min="3" max="10" v-model="seriesCount" @input="updateChartData">
          </div>
          
          <div class="control-group">
            <label>
              最大值: {{ maxValue }}
              <span class="range-value">{{ maxValue }}</span>
            </label>
            <input type="range" min="100" max="1000" step="100" v-model="maxValue" @input="updateChartData">
          </div>
          
          <button class="btn" @click="generateRandomData">
            <i class="fas fa-random"></i> 生成随机数据
          </button>
        </div>
      </div>
      
      <!-- 数据表格 -->
      <div class="chart-card">
        <div class="chart-header">
          <div class="chart-icon">
            <i class="fas fa-table"></i>
          </div>
          <h2 class="chart-title">数据详情</h2>
        </div>
        
        <table class="data-table">
          <thead>
            <tr>
              <th>类别</th>
              <th>数值</th>
              <th>占比</th>
              <th>颜色</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in chartData" :key="index">
              <td>{{ item.name }}</td>
              <td>{{ item.value }}</td>
              <td>{{ calculatePercentage(item.value) }}%</td>
              <td>
                <span 
                  class="color-badge" 
                  :style="{ backgroundColor : (item.itemStyle ? item.itemStyle.color : '#5470c6') }"
                ></span>
              </td>
            </tr>
          </tbody>
        </table>
        
        <div class="data-controls">
          <h3>统计信息</h3>
          <p><strong>图表类型:</strong> {{ getChartTitle() }}</p>
          <p><strong>数据总量:</strong> {{ totalValue }} 单位</p>
          <p><strong>数据类别:</strong> {{ seriesCount }} 个</p>
          <p><strong>最大值:</strong> {{ maxDataValue.value }} ({{ maxDataValue.name }})</p>
          <p><strong>最小值:</strong> {{ minDataValue.value }} ({{ minDataValue.name }})</p>
        </div>
      </div>
    </div>
    
    <footer>
      <p>Vue 2 + ECharts 饼状图示例</p>
    </footer>
  </div>
</template>

<script>
// 引入ECharts
import * as echarts from 'echarts';

export default {
  name: 'PieChartDemo',
  
  data() {
    return {
      chartType: 'basic',
      seriesCount: 6,
      maxValue: 500,
      chartData: [],
      pieChartInstance: null
    }
  },
  
  computed: {
    // 计算总数值
    totalValue() {
      return this.chartData.reduce((sum, item) => sum + item.value, 0);
    },
    
    // 找出最大值
    maxDataValue() {
      if (!this.chartData.length) return { name: '', value: 0 };
      const max = Math.max(...this.chartData.map(item => item.value));
      return this.chartData.find(item => item.value === max) || { name: '', value: 0 };
    },
    
    // 找出最小值
    minDataValue() {
      if (!this.chartData.length) return { name: '', value: 0 };
      const min = Math.min(...this.chartData.map(item => item.value));
      return this.chartData.find(item => item.value === min) || { name: '', value: 0 };
    }
  },
  
  methods: {
    // 生成随机数据
    generateData() {
      const categories = ['产品A', '产品B', '产品C', '产品D', '产品E', 
                         '产品F', '产品G', '产品H', '产品I', '产品J'];
      const colorList = [
        '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
        '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#d7504b'
      ];
      
      const data = [];
      
      for (let i = 0; i < this.seriesCount; i++) {
        const category = i < categories.length ? categories[i] : `产品${String.fromCharCode(65 + i)}`;
        data.push({
          name: category,
          value: Math.floor(Math.random() * this.maxValue) + 50,
          itemStyle: {
            color: colorList[i % colorList.length]
          }
        });
      }
      
      return data;
    },
    
    // 计算百分比
    calculatePercentage(value) {
      if (this.totalValue === 0) return 0;
      return ((value / this.totalValue) * 100).toFixed(1);
    },
    
    // 更新图表数据
    updateChartData() {
      this.chartData = this.generateData();
      this.initPieChart();
    },
    
    // 生成随机数据
    generateRandomData() {
      this.chartData = this.generateData();
      this.initPieChart();
    },
    
    // 更改图表类型
    changeChartType(type) {
      this.chartType = type;
      this.initPieChart();
    },
    
    // 获取图表标题
    getChartTitle() {
      const titles = {
        'basic': '基础饼状图',
        'doughnut': '环形图',
        'rose': '南丁格尔玫瑰图'
      };
      return titles[this.chartType] || '饼状图';
    },
    
    // 初始化饼图
    initPieChart() {
      if (!this.$refs.pieChart) return;
      
      // 销毁现有实例
      if (this.pieChartInstance) {
        this.pieChartInstance.dispose();
      }
      
      // 创建新实例
      this.pieChartInstance = echarts.init(this.$refs.pieChart);
      
      // 根据图表类型设置不同的配置
      let option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle',
          data: this.chartData.map(item => item.name)
        },
        series: []
      };
      
      switch (this.chartType) {
        case 'basic':
          option.series.push({
            name: '销售占比',
            type: 'pie',
            radius: '60%',
            center: ['60%', '50%'],
            data: this.chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              formatter: '{b}: {c} ({d}%)'
            }
          });
          break;
          
        case 'doughnut':
          option.series.push({
            name: '销售占比',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            data: this.chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              formatter: '{b}: {c} ({d}%)'
            },
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            }
          });
          break;
          
        case 'rose':
          option.series.push({
            name: '销售占比',
            type: 'pie',
            radius: ['30%', '70%'],
            center: ['60%', '50%'],
            data: this.chartData,
            roseType: 'area',
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              formatter: '{b}: {c}'
            },
            itemStyle: {
              borderRadius: 8
            }
          });
          break;
      }
      
      // 设置配置项并渲染图表
      this.pieChartInstance.setOption(option);
    },
    
    // 窗口调整大小处理
    handleResize() {
      if (this.pieChartInstance) {
        this.pieChartInstance.resize();
      }
    }
  },
  
  mounted() {
    // 初始化数据
    this.chartData = this.generateData();
    
    // 使用$nextTick确保DOM已经渲染
    this.$nextTick(() => {
      this.initPieChart();
    });
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  
  beforeDestroy() {
    // 组件销毁时销毁图表实例
    if (this.pieChartInstance) {
      this.pieChartInstance.dispose();
      this.pieChartInstance = null;
    }
    
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize);
  },
  
  watch: {
    // 监听数据变化
    chartData: {
      handler() {
        this.$nextTick(() => {
          if (this.pieChartInstance) {
            this.initPieChart();
          }
        });
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.container {
  margin: 0 auto;
  padding: 20px;
  /*
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  */
  max-width: 1200px;
  min-height: 100vh;
}

header {
  text-align: center;
  padding: 20px 0;
  margin-bottom: 30px;
}

h1 {
  font-size: 2.5rem;
  color: #3498db;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1.2rem;
  font-style: italic;
  color: #7f8c8d;
  max-width: 800px;
  margin: 0 auto;
}

.controls {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.btn {
  background: #3498db;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

.btn.active {
  background: #2c3e50;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 25px;
  margin-top: 30px;
}

.chart-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 25px;
  transition: transform 0.3s ease;
}

.chart-card:hover {
  transform: translateY(-5px);
}

.chart-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f1f1f1;
}

.chart-icon {
  width: 40px;
  height: 40px;
  background: #3498db;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
  font-size: 1.2rem;
}

.chart-title {
  font-size: 1.3rem;
  color: #2c3e50;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
  margin-top: 15px;
}

.data-controls {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-top: 20px;
}

.control-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

input[type="range"] {
  width: 100%;
}

.range-value {
  display: inline-block;
  min-width: 40px;
  text-align: center;
  background: #e9ecef;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: bold;
  margin-left: 10px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.data-table th, .data-table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: center;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.data-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.color-badge {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 3px;
  border: 1px solid #ddd;
}

footer {
  text-align: center;
  margin-top: 40px;
  color: #7f8c8d;
  font-size: 0.9rem;
}

@media (max-width: 768px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .chart-wrapper {
    height: 300px;
  }
  
  .controls {
    flex-direction: column;
    align-items: center;
  }
  
  .btn {
    width: 200px;
  }
}
</style>